//
//  CommentList.m
//  RRBI
//
//  Created by kuyuZJ on 16/7/5.
//
//

#import "CommentList.h"
#import "CommentNewListCell.h"
#import "CommentNewListModel.h"
#import "zySheetPickerView.h"
#import "QZTopTextView.h"
#import "CommentShaiXuanView.h"

@interface CommentList ()<UITableViewDelegate,UITableViewDataSource,QZTopTextViewDelegate>
{
    QZTopTextView * _textView;
}
@property(nonatomic,strong) UITableView* tableView;
@property(nonatomic,strong) UIView* headerView;
@property (nonatomic, strong) UIImageView *backImageView;
@property (nonatomic, assign) NSInteger page;

@property(nonatomic,strong) NSMutableArray* arrayData;
@property(nonatomic,strong) NSDictionary* dictData;
@property (nonatomic, strong) CommentNewListModel *commentModel;
/**
 *  type(评论类型，0：全部，1：差评，2：中评；3：好评)
 */
@property(nonatomic,copy) NSString* typeID;
@property (nonatomic, copy) NSString *status;
@property (nonatomic, copy) NSString *huifu;

@property (nonatomic, strong) CommentShaiXuanView *shaiXuanView;


@end

@implementation CommentList

- (NSMutableArray *)arrayData {
    if (!_arrayData) {
        _arrayData = [NSMutableArray array];
    }
    return _arrayData;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title =  @"用户评价";
    
    self.typeID = @"1";
    self.status = @"1";
    self.huifu = @"1";
    
    [self layoutUI];
    _textView =[QZTopTextView topTextView];
    _textView.delegate = self;
    [self.view addSubview:_textView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
static BOOL isSelect = NO;
#pragma mark =====================================================  User interface layout
-(void)layoutUI{
    
    self.shaiXuanView = [[CommentShaiXuanView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
    [self.view addSubview:self.shaiXuanView];
    __weak typeof(self) weakSelf = self;
    self.shaiXuanView.weiHuiFuButtonBlock = ^{
        isSelect = !isSelect;
        if (isSelect) {
            [weakSelf createTanKuangView];
        } else {
            [weakSelf.backImageView removeFromSuperview];
        }
    };
    self.shaiXuanView.TopShuaiXuanButtonBlock = ^(NSInteger index) {
        weakSelf.status = [NSString stringWithFormat:@"%ld",index];
         weakSelf.huifu = @"1";
        [weakSelf getData];
    };
    self.shaiXuanView.BottomShuaiXuanButtonBlock = ^(NSInteger index) {
        weakSelf.typeID = [NSString stringWithFormat:@"%ld",index];
         weakSelf.huifu = @"1";
        [weakSelf getData];
    };
    
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CommentNewListCell class]) bundle:nil] forCellReuseIdentifier:@"commentNewListCell"];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(getMoreData)];
    [self getData];
}

- (void)createTanKuangView {
    [self.backImageView removeFromSuperview];
    self.backImageView = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-15-120, self.shaiXuanView.bounds.size.height-2, 120, 90)];
    self.backImageView.backgroundColor = [UIColor lightGrayColor];
    self.backImageView.userInteractionEnabled = YES;
    [self.view addSubview:self.backImageView];
    
    
    UIButton *quanBuButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, self.backImageView.bounds.size.width, self.backImageView.bounds.size.height/3)];
    quanBuButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [quanBuButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [quanBuButton setTitle:[NSString stringWithFormat:@"全部%@",[self.dictData objectForKey:@"all_count"]] forState:UIControlStateNormal];
    [quanBuButton addTarget:self action:@selector(quanBuButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.backImageView addSubview:quanBuButton];
    
    
    UIButton *weiHuiFuButton = [[UIButton alloc]initWithFrame:CGRectMake(0, self.backImageView.bounds.size.height/3, self.backImageView.bounds.size.width, self.backImageView.bounds.size.height/3)];
    weiHuiFuButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [weiHuiFuButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [weiHuiFuButton setTitle:[NSString stringWithFormat:@"已回复%@",[self.dictData objectForKey:@"yj_huifu_count"]] forState:UIControlStateNormal];
    [weiHuiFuButton addTarget:self action:@selector(weiHuiFuButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.backImageView addSubview:weiHuiFuButton];
    
    UIButton *weiHuiFuChaButton = [[UIButton alloc]initWithFrame:CGRectMake(0, self.backImageView.bounds.size.height/3*2, self.backImageView.bounds.size.width, self.backImageView.bounds.size.height/3)];
    weiHuiFuChaButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [weiHuiFuChaButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [weiHuiFuChaButton setTitle:[NSString stringWithFormat:@"未回复%@",[self.dictData objectForKey:@"huifu_count"]] forState:UIControlStateNormal];
    [weiHuiFuChaButton addTarget:self action:@selector(weiHuiFuChaButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.backImageView addSubview:weiHuiFuChaButton];
    
}

- (void)quanBuButtonAction {
    self.huifu = @"1";
    [self.backImageView removeFromSuperview];
    [self getData];
}
- (void)weiHuiFuButtonAction {
    self.huifu = @"2";
    [self.backImageView removeFromSuperview];
    [self getData];
}
- (void)weiHuiFuChaButtonAction {
    self.huifu = @"3";
    [self.backImageView removeFromSuperview];
    [self getData];
}
#pragma mark - 数据请求
-(void)getData{
    [self getDataWithPageNum:1 isHeader:YES];
}

-(void)getMoreData{
    [self getDataWithPageNum:self.page isHeader:NO];
}

- (void)getDataWithPageNum:(NSInteger)pageNum isHeader:(BOOL)isHeader{
    
    
    AFHTTPSessionManager *mgr=[AFHTTPSessionManager manager];
    NSDictionary* arg = @{
                          @"ru_id":[UserModel sharedInstanced].ru_Id,
                          @"ince":@"seller_user_evaluate",
                          @"type":self.typeID,
                          @"status":self.status,
                          @"huifu":self.huifu,
                          @"page":[NSString stringWithFormat:@"%ld",pageNum],
                          @"pagesize":@"10"
                          };
    
    NSString *URL = [NSString stringWithFormat:@"%@%@",BaseUrl,@"seller_user_evaluate"];
    [mgr POST:URL parameters:arg progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        [WMHelper outPutJsonString:responseObject];
        
        NSInteger flag = [[responseObject objectForKey:@"ret"]integerValue];
        if(flag == 200){
            
            
            self.dictData = responseObject;
            self.shaiXuanView.mainDict = responseObject;
            NSMutableArray *tempArr = [NSMutableArray array];
            tempArr = [CommentNewListModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:@"list"]];
            
            if (isHeader) {
                self.page = 1;
                self.tableView.mj_footer.state = MJRefreshStateIdle;
                [self.arrayData removeAllObjects];
                [self.arrayData addObjectsFromArray:tempArr];
                
                self.page++;
            }else {
                [self.tableView.mj_footer endRefreshing];
                if (tempArr.count > 0) {
                    [self.arrayData addObjectsFromArray:tempArr];
                    self.page++;
                }else{
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    
                }
            }
            
            [self.tableView reloadData];
            
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error)  {
        if (isHeader) {
            [self.tableView.mj_header endRefreshing];
            self.page = 1;
        }else {
            [self.tableView.mj_footer endRefreshing];
            self.page--;
        }
    }];
    
}


#pragma mark =====================================================  <UITableViewDataSource>
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arrayData.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CommentNewListModel *model = self.arrayData[indexPath.row];
    return [model cell_H];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CommentNewListCell* cell = [tableView dequeueReusableCellWithIdentifier:@"commentNewListCell"];
    CommentNewListModel *model = self.arrayData[indexPath.row];
    [cell updataDataWithModel:model];
    __weak typeof(self) weakSelf = self;
    cell.FaQuanButtonBlock = ^{
        [weakSelf faQuanButtonActionWithModel:model];
    };
    
    cell.HuiFuButtonBlock = ^{
        [weakSelf huiFuButtonActionWithModel:model];
    };
    return cell;
}

//发券
- (void)faQuanButtonActionWithModel:(CommentNewListModel *)model {
    [self getShopData:model];
}
//回复
- (void)huiFuButtonActionWithModel:(CommentNewListModel *)model {
    self.commentModel = model;
    [_textView.lpTextView becomeFirstResponder];
}

- (void)sendComment
{
    NSLog(@"%@",_textView.lpTextView.text);
    [self huiFUReq:self.commentModel];
}

#pragma mark - 数据请求
- (void)getShopData:(CommentNewListModel *)model {
    
    AFHTTPSessionManager *mgr=[AFHTTPSessionManager manager];
    NSDictionary* arg = @{
                          @"ru_id":[UserModel sharedInstanced].ru_Id,
                          @"ince":@"seller_coupon_list"
                          };
    
    NSString *URL = [NSString stringWithFormat:@"%@%@",BaseUrl,@"seller_coupon_list"];
    [mgr POST:URL parameters:arg progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        [WMHelper outPutJsonString:responseObject];
        
        NSInteger flag = [[responseObject objectForKey:@"ret"]integerValue];
        if(flag == 200){
            NSArray * strArr  = [responseObject objectForKey:@"list"];
            
            
            NSMutableArray *arr = [NSMutableArray array];
            for (NSInteger i=0; i<strArr.count; i++) {
                
                NSDictionary *dict = strArr[i];
                [arr addObject:[NSString stringWithFormat:@"%@,%@",[dict objectForKey:@"youhui"],[dict objectForKey:@"youxiao_time"]]];
            }
            
            if (strArr.count == 0) {
                [LSOCUtils show:self.view withText:@"暂无优惠券"];
            } else {
            zySheetPickerView *pickerView = [zySheetPickerView ZYSheetStringPickerWithTitle:arr andHeadTitle:@"优惠券" Andcall:^(zySheetPickerView *pickerView, NSString *choiceString) {
                NSString *gidS = @"";
                for (NSInteger i=0; i<strArr.count; i++) {
                    NSDictionary *dict = strArr[i];
                    if ([choiceString isEqualToString:[NSString stringWithFormat:@"%@,%@",[dict objectForKey:@"youhui"],[dict objectForKey:@"youxiao_time"]]]) {
                        gidS = [NSString stringWithFormat:@"%@",[dict objectForKey:@"id"]];
                    }
                }
                
                [self sendQuanReq:model gid:gidS];
                [pickerView dismissPicker];
            }];
            [pickerView show];
            }
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error)  {
        
    }];
    
}

#pragma mark - 发券请求
- (void)sendQuanReq:(CommentNewListModel *)model gid:(NSString *)git {
    
    AFHTTPSessionManager *mgr=[AFHTTPSessionManager manager];
    NSDictionary* arg = @{
                          @"ru_id":[UserModel sharedInstanced].ru_Id,
                          @"gid":git,
                          @"ince":@"seller_give_coupon",
                          @"uid":model.user_id
                          };
    
    NSString *URL = [NSString stringWithFormat:@"%@%@",BaseUrl,@"seller_give_coupon"];
    [mgr POST:URL parameters:arg progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        [WMHelper outPutJsonString:responseObject];
        
        NSInteger flag = [[responseObject objectForKey:@"ret"]integerValue];
        if(flag == 200){
            [LSOCUtils show:self.view withText:[responseObject objectForKey:@"msg"]];
        } else {
            [LSOCUtils show:self.view withText:[responseObject objectForKey:@"msg"]];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error)  {
            [LSOCUtils show:self.view withText:@"发送失败"];
    }];
    
}

#pragma mark - 回复请求
- (void)huiFUReq:(CommentNewListModel *)model{
    
    AFHTTPSessionManager *mgr=[AFHTTPSessionManager manager];
    NSDictionary* arg = @{
                          //@"ru_id":[UserModel sharedInstanced].ru_Id,
                          @"msg":_textView.lpTextView.text,
                          @"ince":@"seller_user_evaluate_comment",
                          @"cid":model.ID
                          };
    
    NSString *URL = [NSString stringWithFormat:@"%@%@",BaseUrl,@"seller_user_evaluate_comment"];
    [mgr POST:URL parameters:arg progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        [WMHelper outPutJsonString:responseObject];
        
        NSInteger flag = [[responseObject objectForKey:@"ret"]integerValue];
        if(flag == 200){
            [LSOCUtils show:self.view withText:[responseObject objectForKey:@"msg"]];
        } else {
             [LSOCUtils show:self.view withText:[responseObject objectForKey:@"msg"]];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error)  {
        [LSOCUtils show:self.view withText:@"回复失败"];
    }];
    
}

#pragma mark =====================================================  Property package

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc]init];
        _tableView.frame = CGRectMake(0, 100, SCREEN_WIDTH, SCREEN_HEIGHT-SafeAreaTopHeight-100);
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}


@end
